<script lang="ts" setup>
import {onMounted, reactive, ref, watch} from 'vue'
import {RegionSelects} from "v-region";
import TagGroup from "@/views/shop/componets/tagGroup.vue";
import ImgUploader from "@/views/shop/componets/imgUploader.vue";
import {getGoodsCategoriesAPI,releaseGoodsAPI} from '@/apis/goods'
import {useUserStore} from '@/stores/user'
import {ComponentSize, ElMessage, FormInstance, FormRules} from 'element-plus'


const parentDynamicTags=ref([])
const imageFile=ref([])

watch(imageFile,(newValue,oldValue)=>{
  form.imgs=newValue
})

const formRef = ref<FormInstance>()

interface RuleForm {
  shopId:string,
  title: string,
  category:string,
  price:string,
  imgs:object[],
  desc:string,
  tags:string[],
  origin:{
    province:string,
    city:string
  },
  stock:string,
  isOnline:string
}

interface GOODS {
  title:string
  stock_quantity:number
  g_price:number
  tags:string
  province:number
  city:number
  category:number
  shop_id:number
  description:string
  isOnline:number
}

const form = ref({
  shopId:useUserStore().myShop.shopId,
  title: '',
  category:'',
  price:'',
  imgs:[],
  desc:'',
  tags:[],
  origin:{
    province:'',
    city:''
  },
  stock:'',
  isOnline:0 // 默认状态改为待审核
})

const rules={
  title:[
    { type: 'string',required: true,message: "必填", trigger: 'blur'},
    {max: 30,message: "标题长度不能超过30位" }
  ],
  category:[
    { type: 'array',required: true,message: "请选择商品种类", trigger: 'blur'},
  ],
  price:[
    { required: true,message: "必填", trigger: 'blur'},
    {type:'number',message: "价格不正确"}
  ],
  imgs:[
    { type: 'array',required: true,message: "至少上传一张图片", trigger: 'blur'},
  ],
  desc:[],
  tags:[],
  origin:[
    {type: 'object', required: true,message: "请选择产地", trigger: 'blur'},
  ],
  stock:[
    { type: 'number',required: true,message: "必填", trigger: 'blur'},
  ],
}


onMounted(()=>{
  getGoodsCategories()
})

watch(parentDynamicTags,(newValue,oldValue)=>{
  form.tags=newValue
})

const options = ref([])
const getGoodsCategories= async ()=>{
  const res=await getGoodsCategoriesAPI()
  if(res.code===200){
   options.value=res.data
  }
}

const onSubmit = () => {
  console.log('submit!')
}


const value = ref([])
const imgUploader=ref()

const props = {
  expandTrigger: 'hover' as const,
}


const handleRelease = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if(imageFile.value.length===0){
        ElMessage({
          type:'error',
          message:"至少上传一张图片"
        })
        return
      }
      if(form.value.origin.city===undefined){
        ElMessage({
          type:'error',
          message:"请选择产地"
        })
        return
      }
      //装载图片
      imgUploader.value.submitUpload()
      releaseGoods()
    } else {
      console.log('error submit!', fields)
    }
  })
}

const releaseGoods=async ()=>{
  form.value.category=form.value.category[form.value.category.length-1]
  form.value.imgs=imageFile.value
  form.value.tags=parentDynamicTags.value

  const goods=ref<GOODS>()
  goods.shop_id=useUserStore().myShop.shopId
  goods.title=form.value.title
  goods.category=form.value.category
  goods.g_price=form.value.price
  goods.description=form.value.desc
  goods.tags=''
  parentDynamicTags.value.forEach((tag,index)=>{
    goods.tags+=(index===parentDynamicTags.value.length-1?tag:tag+',')
  })
  goods.province=form.value.origin.province
  goods.city=form.value.origin.city
  goods.stock_quantity=form.value.stock
  goods.isOnline=0 // 默认状态改为待审核

  console.log('goods',goods)

  const formData= new FormData()
  const imageFiles=imgUploader.value.getImageFile()
  //转成Blob类型，不然会乱码
  const goodsJsonBlob = new Blob([JSON.stringify(goods)], { type: 'application/json' });

  formData.append('good',goodsJsonBlob)
  imageFiles.value.forEach(file => {
    formData.append('goodsImages', file.raw);
  });

  const res=await releaseGoodsAPI(formData)
  if(res.code===200){
    ElMessage({
      type:'success',
      message:"商品发布成功，等待管理员审核"
    })
    //重置表单
    formRef.value.resetFields()
    //重置图片
    imgUploader.value.clearFiles()
  }else{
    ElMessage({
      type:'error',
      message:"发布失败"
    })
  }

}

</script>

<template>
  <div class="releasePanel">
    <h2>发布商品</h2>
    <el-form :model="form" :rules="rules" ref="formRef" label-width="auto" style="max-width: 600px">
     <el-form-item label="商品标题" prop="title">
       <el-input v-model="form.title"></el-input>
     </el-form-item>
      <el-form-item label="商品分类" prop="category">
        <el-cascader
            v-model="form.category"
            :options="options"
            :props="props"
            :show-all-levels="false"
            @change="handleChange"
        />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model.number="form.price"></el-input>
      </el-form-item>
      <el-form-item label="商品图片" >
        <img-uploader v-model:file="imageFile" ref="imgUploader"></img-uploader>
      </el-form-item>
      <el-form-item label="商品描述" prop="desc">
        <el-input v-model="form.desc" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="标签">
        <tag-group v-model="parentDynamicTags"/>
      </el-form-item>
      <el-form-item label="原产地" prop="origin">
        <RegionSelects :area="false"  v-model="form.origin"/>
      </el-form-item>
      <el-form-item label="库存量" prop="stock">
        <el-input v-model.number="form.stock"></el-input>
      </el-form-item>

      <el-form-item >
        <el-button type="primary" @click="handleRelease(formRef)" >发布</el-button>
        <el-button type="warning" >存草稿</el-button>
        <el-button type="danger" >重置</el-button>
      </el-form-item>


    </el-form>
  </div>
</template>

<style scoped lang="less">
.releasePanel {
  width: 100%;
  max-width: 990px;
  min-height: 1000px;
  background-color: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  
  h2 {
    margin: 0 0 30px 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
  }
}

:deep(.el-form) {
  max-width: 600px;
  
  .el-form-item {
    margin-bottom: 24px;
    
    .el-input, .el-select, .el-cascader, .el-textarea {
      width: 100%;
    }
    
    .el-textarea {
      .el-textarea__inner {
        min-height: 100px;
      }
    }
    
    .el-button {
      margin-right: 10px;
      padding: 10px 20px;
      font-weight: 500;
      
      &:last-child {
        margin-right: 0;
      }
    }
  }
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
  transition: all 0.3s;
  
  &:hover {
    border-color: #c0c4cc;
  }
  
  &.is-focus {
    border-color: #007bff;
    box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
  }
}

:deep(.el-cascader) {
  .el-cascader__tags {
    max-width: 100%;
  }
}

:deep(.el-upload) {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
  transition: all 0.3s;
  
  &:hover {
    border-color: #007bff;
    background-color: #f0f7ff;
  }
}
</style>